package ss.lianft.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import ss.lianft.model.*;
import ss.lianft.tools.Common;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/dept")
public class DeptController extends BaseController {

    @RequestMapping("mgr")
    public String index(){
        return "dept/dept";
    }

    @Autowired
    public SQLManager sqlManager;

    @RequestMapping("list")
    @ResponseBody
    public Map<String,Object> depts(Org org, @RequestParam("page") int page, @RequestParam("limit") int limit){
        PageQuery query = new PageQuery();
        if(StringUtils.isBlank(org.getOrgDesc())){
            org.setOrgDesc(null);
        }
        query.setParas(org);
        query.setPageNumber(page);
        query.setPageSize(limit);
        sqlManager.pageQuery("org.list",Org.class,query);
        return tableData(query);
    }

    @RequestMapping("create")
    public String preCreate(){
        return "dept/deptAU";
    }

    @RequestMapping("doAU")
    @ResponseBody
    public String create(Org org){
        try {
            if(org.getId()==null){
                org.setCreateTime(new Date());
                org.setUpdateTime(new Date());
                sqlManager.insert(org);
            }else{
                org.setUpdateTime(new Date());
                sqlManager.updateById(org);
            }
            return "success";
        }catch(Exception e){
            e.printStackTrace();
            return "failed";
        }
    }

    @RequestMapping("view")
    public String view(Model model, @RequestParam("id") int id){
        Org org = sqlManager.unique(Org.class,id);
        model.addAttribute("org",org);
        return "dept/deptView";
    }

    @RequestMapping("update")
    public String update(Model model, @RequestParam("id") int id){
        Org org = sqlManager.unique(Org.class,id);
        model.addAttribute("org",org);
        return "dept/deptAU";
    }

    @RequestMapping("del")
    public String del(Model model,@RequestParam("id") int id){
        sqlManager.deleteById(Org.class,id);
        return "success";
    }

    @RequestMapping("orgUser")
    public String preOrgUsers(Model model,@RequestParam("id") int id){
        List<User> users = sqlManager.all(User.class);
        UserOrg uo = new UserOrg();
        uo.setOrgId(id);
        List<UserOrg> uos = sqlManager.select("userOrg.list",UserOrg.class,uo);
        users.forEach(user->{
            uos.forEach(uuo->{
                if(uuo.getUserId()==user.getId()){
                    user.setPassword("checked");
                }
            });
        });
        model.addAttribute("users",users);
        model.addAttribute("orgId",id);
        return "dept/deptUser";
    }

    @RequestMapping("orgFuncs")
    public String preOrgFuncs(Model model,@RequestParam("id") int id){
        Menu menuQuery = new Menu();
        menuQuery.setParentId(0);
        List<MenuView> menus = sqlManager.select("menu.list",MenuView.class,menuQuery);

        FuncOrg fo = new FuncOrg();
        fo.setOrgId(id);
        List<FuncOrg> fos = sqlManager.select("funcOrg.list",FuncOrg.class,fo);
        menus.forEach(menuView -> {
            for(FuncOrg foo : fos){
                if(menuView.getMenuFunc()==foo.getFuncId()){
                    menuView.setMenuName("checked");
                    break;
                }
            }
            menuQuery.setParentId(menuView.getId());
            List<Menu> childSrcMenus = sqlManager.select("menu.list",Menu.class,menuQuery);
            childSrcMenus.forEach(childSrcMenu->{
                for(FuncOrg foo : fos){
                    if(childSrcMenu.getMenuFunc() == foo.getFuncId()){
                        childSrcMenu.setMenuName("checked");
                        break;
                    }
                }
            });
            menuView.setSubMenu(childSrcMenus);
        });

        model.addAttribute("menus",menus);
        model.addAttribute("orgId",id);
        return "dept/deptAuth";
    }

    @RequestMapping(value="doOrgFunc",method= RequestMethod.POST)
    @ResponseBody
    @Transactional
    public String orgFuncs(@RequestParam("funcIds") Integer[] funcIds,@RequestParam("orgId") int orgId){
        sqlManager.executeUpdate(new SQLReady("delete from func_org where org_id = ?",orgId));
        for(Integer funcId : funcIds){
            FuncOrg fo = new FuncOrg();
            fo.setOrgId(orgId);
            fo.setFuncId(funcId);
            fo.setCreateTime(new Date());
            fo.setUpdateTime(new Date());
            sqlManager.insert(fo);
        }
        Common.flushAuth();//刷新当前用户权限
        return "success";
    }

    @RequestMapping(value="doOrgUser",method= RequestMethod.POST)
    @ResponseBody
    @Transactional
    public String orgUsers(@RequestParam("userIds") Integer[] userIds,@RequestParam("orgId") int orgId){
        sqlManager.executeUpdate(new SQLReady("delete from user_org where org_id = ?",orgId));
        for (Integer userId : userIds) {
            UserOrg uo = new UserOrg();
            uo.setUserId(userId);
            uo.setOrgId(orgId);
            uo.setCreateTime(new Date());
            uo.setUpdateTime(new Date());
            sqlManager.insert(uo);
        }
        return "success";
    }
}
